package org.example.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.example.service.UserService2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {
    @Reference
    UserService2 userService2;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String clientPath = request.getPath().toString();
        System.out.println(clientPath);

        String[] paths = clientPath.split("/");
        // /api/user/..., /api/code/...
        if(paths[2].equals("user") || paths[2].equals("code") ){
            return chain.filter(exchange);
        }
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        for(String key:cookies.keySet()){
            if(key.equals("token")){
                String token = cookies.get(key).get(0).getValue();
                String res = userService2.info(token);
                if(!res.equals("token not valid")){
                    //token valid
                    return chain.filter(exchange);
                }
                break;
            }
        }

        String data = "Request be denied!";
        DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
        response.setStatusCode(HttpStatus.valueOf(401));
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
